--通通换成api以达到提高兼容性的目的
--By 青青草原扛把子
GLOBAL.setmetatable(env,{__index=function(t,k) return GLOBAL.rawget(GLOBAL,k) end})

local Text = require"widgets/text"
local Menu = require "widgets/menu"
local Image = require "widgets/image"
local ImageButton = require "widgets/imagebutton"

--------------------<修复用的API>--------------------
--[[禁用刷物
GLOBAL.c_give = function()
  GetPlayer().components.talker:Say("\230\137\155\230\138\138\229\173\144\232\175\180\228\184\141\232\174\169\229\136\183\231\137\169\229\147\166\239\188\129")
  return false
end]]

--修复与item info冲突
for _, moddir in ipairs(KnownModIndex:GetModsToLoad()) do
  local name = KnownModIndex:GetModInfo(moddir).name
  local author = KnownModIndex:GetModInfo(moddir).author
  if name and author then
    if string.find(name, "Item Info") and string.find(author, "Jakeris") then
      AddClassPostConstruct("widgets/iteminfo_desc", function(self)
     local function FormatInt(value)
       return math.floor(value + 0.5)
        end
  function self:AddArmorRow(base_inst, inst)
   local hp = base_inst.components.armor.maxcondition  * inst.components.armor:GetPercent()

   local img1 = Image("images/iteminfo_images.xml", "armor.tex")
   local txt1 = Text(NUMBERFONT, 42)
   txt1.inst.TextWidget:SetString(FormatInt(inst.components.armor.absorb_percent * 100) .. "%")

   local img2 = Image("images/iteminfo_images.xml", "health.tex")
   local txt2 = Text(NUMBERFONT, 42)
   txt2.inst.TextWidget:SetString(FormatInt(hp))


   self:AddChild2(img1, txt1, img2, txt2)
  end
      end)
    end
  end
end

--修复小切复制，有点不靠谱
AddPlayerPostInit(function(inst)
  inst:DoPeriodicTask(0, function()
    local count = 0
    for i,v in pairs(Ents) do
      if v.prefab == "chester" or v.prefab == "packim" or v.prefab == "ro_bin" then
        if count < 1 then
          count = count + 1
        else
          v:Remove()
        end
      end
    end
  end)
end)

--修复进冒险大门崩溃
AddComponentPostInit("health", function(self)
  function self:SetAbsorbAmount(amount)
    self.absorb = amount
  end
end)

--修复哈姆雷特击杀小偷造成的崩溃问题
AddGlobalClassPostConstruct("entityscript", "EntityScript", function(self)
  function self.GetDistanceSqToInst(self, inst)
    local p1x, p1y, p1z = self.Transform:GetWorldPosition()
    local p2x, p2y, p2z = inst.Transform:GetWorldPosition()
    if p1x and p1z and p2x and p2z then
      return distsq(p1x, p1z, p2x, p2z)
    else
      return 100
    end
  end
end)

--解决暗影斗篷的存放优先级比添加燃料高的问题，渊哥牛逼！
AddComponentPostInit("playeractionpicker", function(self)
  function self:GetUseItemActions(target, useitem, right)
    local actions = {}

    if target.CollectUseActions and target:is_a(EntityScript) then
        target:CollectUseActions(useitem, actions, right)
    else
        for k,v in pairs(useitem.components) do
            if v.CollectUseActions and target:is_a(EntityScript) then
                v:CollectUseActions(self.inst, target, actions, right)
            end
        end
    end
    local acts = self:SortActionList(actions, target, useitem)
    if acts ~= nil then
      for k,v in pairs(acts) do
        if v.action == ACTIONS.STORE and target:HasTag("vortex_cloak") then
          if self.inst:GetIsWet() then
            v.action = ACTIONS.ADDWETFUEL
          else
            v.action = ACTIONS.ADDFUEL
          end
        end 
      end
    end

    return acts
  end
end)

--小凤凰收集，没有这收集的作物会消失
AddComponentPostInit("pickable", function(self)
  local old_Pick = self.Pick
  function self:Pick(picker)
    if picker and picker:HasTag("yamcheb") and picker.components.container then
      if self.canbepicked and self.caninteractwith then

		if self.transplanted then
			if self.cycles_left ~= nil then
				self.cycles_left = self.cycles_left - 1
			end
		end

		if self.shouldwither then
			if self.protected_cycles ~= nil then
				self.protected_cycles = self.protected_cycles - 1
			end
		end
		
		local loot = nil
        if picker and picker.components.container and self.product then
            loot = SpawnPrefab(self.product)

            if loot then
	            if self.numtoharvest > 1 and loot.components.stackable then
	            	loot.components.stackable:SetStackSize(self.numtoharvest)	            	
	            end

				self.inst:ApplyInheritedMoisture(loot)

		        picker:PushEvent("picksomething", {object = self.inst, loot= loot})
                picker.components.container:GiveItem(loot, nil, Vector3(TheSim:GetScreenPos(self.inst.Transform:GetWorldPosition())))
            end
        end
        
        if self.onpickedfn then
            self.onpickedfn(self.inst, picker, loot)
        end
       
        self.canbepicked = false
        self.hasbeenpicked = true
        
        if not self.paused and not self.withered and self.baseregentime and (self.cycles_left == nil or self.cycles_left > 0) and self.inst:IsValid() then
        	self.regentime = self.baseregentime * self:GetGrowthMod()
			self.task = self.inst:DoTaskInTime(self.regentime, OnRegen, "regen")
			self.targettime = GetTime() + self.regentime
		end
        
        self.inst:PushEvent("picked", {picker = picker, loot = loot, plant = self.inst})
      end
	else
	  return old_Pick(self, picker)
	end
  end
end)

--小凤凰收集
AddComponentPostInit("harvestable", function(self)
  local old_Harvest = self.Harvest
  function self:Harvest(picker)
    if picker and picker:HasTag("yamcheb") and picker.components.container then
      if self:CanBeHarvested() then
        local produce = self.produce
        self.produce = 0
        
        if self.onharvestfn then
            self.onharvestfn(self.inst, picker, produce)
        end
        
        if self.product then
	        picker:PushEvent("harvestsomething", {object = self.inst})
            for i = 1, produce, 1 do
                local loot = SpawnPrefab(self.product)
                if loot then
                    self.inst:ApplyInheritedMoisture(loot)
                    picker.components.container:GiveItem(loot)
                end
            end
        end
        self:StartGrowing()
        return true
      end
	else
      return old_Harvest(self, picker)
	end
  end
end)

--小凤凰收集作物
AddComponentPostInit("crop", function(self)
  function self:Harvest(harvester)
    if self.matured or self.withered then
        local product = nil
        if self.grower and self.grower:HasTag("fire") or self.inst:HasTag("fire") then
            local temp = SpawnPrefab(self.product_prefab)
            if temp.components.cookable and temp.components.cookable.product then
                product = SpawnPrefab(temp.components.cookable.product)
            else
                product = SpawnPrefab("seeds_cooked")
            end
            temp:Remove()
        else
            product = SpawnPrefab(self.product_prefab)
        end

        if product then
            self.inst:ApplyInheritedMoisture(product)
        end

        if harvester ~= nil and not harvester:HasTag("yamcheb") and harvester.components.inventory then
          harvester.components.inventory:GiveItem(product, nil, Vector3(TheSim:GetScreenPos(self.inst.Transform:GetWorldPosition())))
        elseif harvester ~= nil and harvester:HasTag("yamcheb") and harvester.components.container then
          harvester.components.container:GiveItem(product, nil, Vector3(TheSim:GetScreenPos(self.inst.Transform:GetWorldPosition())))
        end

        ProfileStatsAdd("grown_"..product.prefab) 
        
        self.matured = false
        self.withered = false
        self.inst:RemoveTag("withered")
        self.growthpercent = 0
        self.product_prefab = nil

        if self.grower and self.grower.components.grower then
            self.grower.components.grower:RemoveCrop(self.inst)
            self.grower = nil
        else
            self.inst:Remove()
        end
        
        return true
    end
  end
end)

--小凤凰收集食物
AddComponentPostInit("stewer", function(self)
  local old_StewerHarvest = self.Harvest
  function self:Harvest( harvester )
    if harvester ~= nil and harvester:HasTag("yamcheb") and harvester.components.container then
	  if self.done then
		if self.onharvest then
			self.onharvest(self.inst)
		end
		self.done = nil
		if self.product then
			if harvester then --and harvester.·inventory then
				local loot = nil
				if self.product ~= "spoiledfood" then
					loot = SpawnPrefab(self.product)

					if loot and loot.components.perishable then
						loot.components.perishable:SetPercent( self.product_spoilage)
						loot.components.perishable:LongUpdate(GetTime() - self.targettime)
						loot.components.perishable:StartPerishing()
					end
				else
					loot = SpawnPrefab("spoiled_food")
				end
				
				if loot then                    
                    loot.targetMoisture = 0
					loot:DoTaskInTime(2*FRAMES, function()
						if loot.components.moisturelistener then 
							loot.components.moisturelistener.moisture = loot.targetMoisture
							loot.targetMoisture = nil
							loot.components.moisturelistener:DoUpdate()
						end
					end)
					harvester.components.container:GiveItem(loot, nil, Vector3(TheSim:GetScreenPos(self.inst.Transform:GetWorldPosition())))
				end
			end
			self.product = nil
			self.spoiltargettime = nil

			if self.spoiltask then 
				self.spoiltask:Cancel()
				self.spoiltask = nil
			end
		end
		
		if self.inst.components.container and not self.inst:HasTag("flooded") then		
			self.inst.components.container.canbeopened = true
		end
		
		return true
	  end
	else
      return old_StewerHarvest(self, harvester)
	end
  end
end)

--[[护甲不叠加
AddComponentPostInit("inventory", function(self)
  function self:ApplyDamage(damage, attacker, weapon)
    local old_damage = damage
    for k,v in pairs(self.equipslots) do
        if v.components.resistance and v.components.resistance:HasResistance(attacker, weapon) then
            return 0
        end
    end

    local armor_absorb = 0
    local Armor_
    
    for k,v in pairs(self.equipslots) do
        if v.components.armor then
        if v.components.armor.absorb_percent > armor_absorb then Armor_ = v end
        armor_absorb = math.max(armor_absorb,v.components.armor.absorb_percent)
       end
    end
    for k,v in pairs(self.equipslots) do
        if v.components.armor and v.components.armor.tags then
        if v.components.armor.absorb_percent > armor_absorb then Armor_ = v end
        armor_absorb = math.max(armor_absorb,v.components.armor.absorb_percent)
        end
    end   
    if Armor_ then
      damage = Armor_.components.armor:TakeDamage(damage, attacker, weapon)
    end
    return damage
  end
end)
--]]
--------------------<增加的界面>--------------------
local Mod_language =  GetModConfigData("modlanguage")
if (Mod_language == "auto" and IsEnglish()) or Mod_language == "english" then
  EN = true
end

--未兼容哈姆雷特的警告界面
AddClassPostConstruct("widgets/controls", function(self)
  if GetPlayer().components.age and GetPlayer().components.age:GetAge() == 0 then
    if not IsDLCEnabled(PORKLAND_DLC) then
      self.wbg = self:AddChild(Image("images/globalpanels.xml", "small_dialog.tex"))
      self.wbg:SetVAnchor(0)
      self.wbg:SetHAnchor(0)
      self.wbg:SetPosition(0,20,0)
      self.wbg:SetScale(1.3, 1.6, 1.3)
      self.wbg.bgshow = true

      self.wbg2 = self.wbg:AddChild(Image())
      self.wbg2:SetVAnchor(0)
      self.wbg2:SetHAnchor(0)
      self.wbg2:SetPosition(0,20,0)

      self.text1 = self.wbg2:AddChild(Text(TITLEFONT, 65))
      self.text1:SetPosition(0, 110, 0)
      self.text1:SetString(EN and "Warning" or "\232\173\166\229\145\138")

      self.text2 = self.wbg2:AddChild(Text(TITLEFONT, 40))
      self.text2:SetPosition(0, 10, 0)
      self.text2:SetString(EN and "This save is not compatible with Hamlet DLC,\nwhich may cause some logical errors." or "\230\163\128\230\181\139\229\136\176\230\156\172\229\173\152\230\161\163\230\156\170\229\133\188\229\174\185\229\147\136\229\167\134\233\155\183\231\137\185DLC\n\229\143\175\232\131\189\228\188\154\229\164\167\229\135\160\231\142\135\229\135\186\231\142\176\230\184\184\230\136\143\229\180\169\230\186\131\231\154\132\230\131\133\229\134\181")

      self.bb = self.wbg2:AddChild(ImageButton())
      self.bb:SetPosition(0, -100, 0)
      self.bb:SetScale(0.8)
      self.bb:SetText(EN and "I see!" or "\230\136\145\231\159\165\233\129\147\228\186\134")
      self.bb:SetOnClick(function() self.wbg:Hide() end)
    end
  end
end)

--[[技能按钮界面
AddClassPostConstruct("widgets/controls", function(self)
  if GetPlayer().prefab == "musha" then  --人物限制
    self.skill_bg = self:AddChild(Image())
    self.skill_bg:SetVAnchor(0)
    self.skill_bg:SetHAnchor(0)
    self.skill_bg:SetPosition(0,-250,0)
    self.skill_bg:SetScale(1)
    self.skill_bg:Hide()

    local button_x = 160
    local skill_buttons1 = {}
    local skill_buttons2 = {}

    --第一排
    table.insert(skill_buttons1, {text= EN and "Shadow" or "\229\189\177\229\173\144", cb=function() skill_shadow() end })
    table.insert(skill_buttons1, {text= EN and "Shield" or "\230\138\164\231\155\190", cb=function() skill_cure() end })
    table.insert(skill_buttons1, {text= EN and "Power attack" or "\233\151\170\231\148\181", cb=function() skill_lightning() end })
    table.insert(skill_buttons1, {text= EN and "Arong" or "\229\176\143\231\137\155", cb=function() order_arong() end })
    table.insert(skill_buttons1, {text= EN and "Dall" or "\230\161\130\230\160\145", cb=function() order_dall() end })
    table.insert(skill_buttons1, {text= EN and "valkyrie" or "\229\165\179\230\173\166\231\165\158", cb=function() skill_valkyrie() end })
    table.insert(skill_buttons1, {text= EN and "Music" or "\229\175\187\229\174\157/\233\159\179\228\185\144", cb=function() skill_dogs() end })

    self.menu1 = self.skill_bg:AddChild(Menu(skill_buttons1, button_x, true))
    self.menu1:SetPosition(-(button_x+(#skill_buttons1-1))-20, 0, 0)
    self.menu1:SetScale(0.4)

    --第二排
    table.insert(skill_buttons2, {text= EN and "Level info" or "\231\173\137\231\186\167\228\191\161\230\129\175", cb=function() level_info() end })
    table.insert(skill_buttons2, {text= EN and "Skill info" or "\230\138\128\232\131\189\228\191\161\230\129\175", cb=function() skill_info() end })
    table.insert(skill_buttons2, {text= EN and "Visual Hold" or "\233\148\129\229\174\154\229\164\150\232\178\140", cb=function() hold_visual() end })
    table.insert(skill_buttons2, {text= EN and "Yamche Battle" or "\229\135\164\229\135\176:\230\136\152\230\150\151", cb=function() follow_yamche() end })
    table.insert(skill_buttons2, {text= EN and "Yamche growup" or "\229\135\164\229\135\176:\230\136\144\233\149\191", cb=function() yamche_growup_key() end })
    table.insert(skill_buttons2, {text= EN and "Yamche Gather" or "\229\135\164\229\135\176:\230\148\182\233\155\134", cb=function() yamche2() end })
    table.insert(skill_buttons2, {text= EN and "Sleeping" or "\231\157\161\232\167\137/\233\134\146\230\157\165", cb=function() sleeping_princess() end })

   self.menu2 = self.skill_bg:AddChild(Menu(skill_buttons2, button_x, true))
   self.menu2:SetPosition(-(button_x+(#skill_buttons2-1))-20, -30, 0)
   self.menu2:SetScale(0.4)
  end
end)


--显示或隐藏技能按钮
local HealthBadge = GLOBAL.require "widgets/healthbadge"

 function HealthBadge:OnTouchStart(id, x, y)
  local player = GetPlayer()
  --player.SkillBg = not player.SkillBg
    --if player.SkillBg then
      player.HUD.controls.skill_bg:Show()
    --else
      --player.HUD.controls.skill_bg:Hide()
    --end
 end
 --]]